/**
 * @Description: 正交投影相机模拟第三人称视角行为
 * @author Beon
 * @date 2022/4/19
*/
import * as THREE from 'three';
import { PerspectiveCamera } from 'three/src/cameras/PerspectiveCamera';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import direction from './Direction';
import { subscribe } from '../../../../utils/tools/tools';

export class Camera {
  camera: PerspectiveCamera
  orbit: OrbitControls

  constructor() {
    this.camera = Camera.createCamera();
    this.orbit = new OrbitControls(this.camera, document.getElementById('game_canvas') as HTMLElement);
    // 关闭右键平移
    this.orbit.enablePan = false;
    subscribe.on('directionAn', 'camera', this.cameraAnimate.bind(this));
  }

  private static createCamera() {
    const camera = new THREE.PerspectiveCamera(50, document.body.offsetWidth / document.body.offsetHeight, 0.1, 100);
    camera.position.set(0, 10, -8);
    return camera;
  }

  private cameraAnimate(param: {
    vector3Direction: THREE.Vector3,
    changeVector3: THREE.Vector3
  }) {
    const {
      vector3Direction,
      changeVector3
    } = param;
    // 根据人物改变相机中心点
    this.camera.lookAt(vector3Direction);
    this.orbit.target = vector3Direction;

    // 添加变化值
    this.camera.position.add(changeVector3);

    // 摄像头缩放功能体现速度
    this.camera.zoom = 1 - direction.moveSpeed * 2;
    this.camera.updateProjectionMatrix();

    // 将相机定位信息给定位计算
    direction.Vector3Camera.copy(this.camera.position);
  }
}
